<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="orderNo">
              <el-input v-model="filters.orderNo" clearable placeholder="订单编号"></el-input>
            </el-form-item>
            <el-form-item prop="originNo">
              <el-input v-model="filters.originNo" clearable placeholder="交易编号"></el-input>
            </el-form-item>
            <el-form-item prop="goodsName">
              <el-input v-model="filters.goodsName" clearable placeholder="产品名称"></el-input>
            </el-form-item>
            <el-form-item prop="orderType">
              <el-select v-model="filters.orderType" placeholder="订单类型" clearable>
                <el-option v-for="item in alarmOrderTypeList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="alarmType">
              <el-select v-model="filters.alarmType" placeholder="报警类型" clearable>
                <el-option v-for="item in EAlarmTypeList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="orderSource">
              <el-select v-model="filters.orderSource" placeholder="订单来源" clearable>
                <el-option v-for="item in alarmOrderSourceList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="beeperId">
              <el-select v-model="filters.beeperId" placeholder="呼叫器" clearable filterable>
                <el-option v-for="item in beeperList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="businessId">
              <el-select v-model="filters.businessId" clearable filterable placeholder="商户">
                <el-option v-for="item in businessList" :key="item.id" :value="item.id" :label="item.name"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="orderState">
              <el-select v-model="filters.orderState" placeholder="订单状态" clearable>
                <el-option v-for="item in orderStateList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="payState">
              <el-select v-model="filters.payState" placeholder="支付状态" clearable>
                <el-option v-for="item in payStateList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="payType">
              <el-select v-model="filters.payType" placeholder="支付方式" clearable>
                <el-option v-for="item in payTypeList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="priceRange">
              <price-range v-model="filters.priceRange"></price-range>
              <!-- <el-input
                        v-model="filters.realAmountMin"
                        clearable
                        placeholder="支付金额"
                ></el-input> -->
            </el-form-item>
            <el-form-item prop="errorState">
              <el-select v-model="filters.errorState" placeholder="异常状态" clearable>
                <el-option v-for="item in errorStateList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="date">
              <el-dropdown @command="handleTimeType">
                <el-button type="primary"> {{ filters.dateType === 1 ? '下单时间' : '支付时间' }}<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
                <el-dropdown-menu>
                  <el-dropdown-item command="1"> 下单时间 </el-dropdown-item>
                  <el-dropdown-item command="2"> 支付时间 </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-date-picker
                v-model="filters.date"
                :clearable="true"
                type="datetimerange"
                range-separator="至"
                start-placeholder="订单查询开始日期"
                end-placeholder="订单查询结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
            <el-button type="danger" plain icon="fa fa-hand-rock-o" v-has="permissionAdd" @click="handleClickBatchOperate(20)" size="mini"> 批量完成订单</el-button>
            <el-button type="success" icon="el-icon-folder" v-has="permissionExport" size="mini" @click="handleExport()">导出</el-button>
            <el-button type="warning" icon="el-icon-folder" v-has="permissionSettleRecord" size="mini" @click="handleExportSR()">导出结算记录</el-button>

            <el-button type="primary" v-if="userRole === 1 && detailRole === 5" v-has="permissionScreen" plain icon="el-icon-position" @click="toLargeScreen()" size="mini">大屏设置器</el-button>
            <el-button v-has="permissionReset" plain type="primary" icon="el-icon-menu" size="mini" @click="handleResetSplitOrder()">重置订单分账</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table
        ref="table"
        :data="dataList"
        :fit="true"
        highlight-current-row
        v-loading="listLoading"
        @row-click="$refs.table.toggleRowSelection($event)"
        @selection-change="handleSelectionChange"
        @click.stop=""
        element-loading-text="数据加载中，请稍后..."
        empty-text="对不起，没有找到相关数据！"
      >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column align="center" width="90" label="下单日期" prop="createDate"></el-table-column>
        <el-table-column align="center" width="100" label="订单编号" prop="orderNo"> </el-table-column>
        <el-table-column align="center" width="100" label="订单类型">
          <template slot-scope="scope">
            <el-tag size="mini" effect="dark" :type="formatOrderTypes(scope.row.orderType)">{{ formatOrderType(scope.row.orderType) }}</el-tag>
            <div style="color: red" v-if="scope.row.alarmType">
              <span>{{ $Filters.formatAlarmType(scope.row.alarmType) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="100" label="订单来源">
          <template slot-scope="scope">
            <el-tag size="mini" effect="dark" :type="$Filters.formatOrderSources(scope.row.orderSource)">{{ $Filters.formatOrderSource(scope.row.orderSource) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" width="125" label="呼叫器">
          <template slot-scope="scope">
            <span>{{ scope.row.equipName }}</span
            ><br />
            <span>
              {{ scope.row.equipCode }}
              <el-tooltip v-if="scope.row.beeperRemark" :content="scope.row.beeperRemark" placement="top">
                <i class="el-icon-info" style="color: #ff4d4f"></i>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户地址" prop="address" width="150px"> </el-table-column>
        <el-table-column align="center" label="商户/部门" width="150px">
          <template slot-scope="scope">
            <span>{{ scope.row.businessName }}</span
            ><br />
            <span>{{ scope.row.departName }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column align="center" label="服务员" prop="waiterName" width="100px">
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.transferOrderFlag" title="查看记录" style="cursor: pointer" type="danger" size="mini" effect="dark" @click="getTransferOrderRecord(scope.row)">转</el-tag>
              {{ scope.row.waiterName }}
            </div>
          </template>
        </el-table-column>-->
        <el-table-column align="center" width="120" label="产品名称" prop="goodsNames">
          <template slot-scope="scope">
            <el-tag v-for="(item, index) in scope.row.orderTag" :key="index" :color="item.color" size="mini" effect="dark" style="border: none; margin-right: 2px">
              {{ item.tagName }}
            </el-tag>
            <span>{{ scope.row.goodsNames }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付信息" width="120" align="center">
          <template slot-scope="scope">
            <span>总数: {{ scope.row.nums }}</span><br />
            <span>金额: {{ scope.row.realAmount }}</span><br />
            <span>{{ formatPayType(scope.row.payType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付状态" align="center" width="100px">
          <template slot-scope="scope">
            <div>
              <el-tag size="mini" effect="dark" :type="formatPayStates(scope.row.payState)">
                {{ formatPayState(scope.row.payState) }}
              </el-tag>
              <div style="color: red" v-if="scope.row.appointmentState > 0">
                <span v-if="scope.row.appointmentState === 1">预约中</span>
                <span v-if="scope.row.appointmentState === 3">预约失败</span>
                <span v-if="scope.row.appointmentState === 5">预约成功</span>
                <span v-if="scope.row.appointmentState === 7">预约取消</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="100px" align="center">
          <template slot-scope="scope">
            <div>
              <el-tag size="mini" effect="dark" :color="formatOrderStates(scope.row.orderState)" style="border: none">
                {{ formatOrderState(scope.row.orderState) }}
              </el-tag>
              <div style="color: red" v-if="scope.row.errorState">
                <span v-if="scope.row.errorState === 1">超时未接单</span>
                <span v-if="scope.row.errorState === 2">商户取消</span>
                <span v-if="scope.row.errorState === 3">用户申请取消</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="打印状态" width="100px" align="center">
          <template slot-scope="scope">
            <el-tag :type="formatPrintStates(scope.row.printState)" effect="dark" size="mini">{{ formatPrintState(scope.row.printState) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" width="90" label="接单日期" prop="acceptDate"> </el-table-column>
        <el-table-column align="center" width="90" label="完成日期" prop="completeDate"> </el-table-column>
        <el-table-column label="操作" width="190" fixed="right">
          <template slot-scope="scope">
            <el-button v-has="permissionTakeOrder" v-if="scope.row.orderState === 1" @click="handleTakeOrder(scope.row)" size="mini">接单</el-button>
            <el-button v-has="permissionDelOrder" v-if="scope.row.orderState === 15" @click="handleDelOrder(scope.row)" size="mini">删除</el-button>
            <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionOperationRecord" @click.native="handleOperationRecord(scope.row)"> 操作记录 </el-dropdown-item>

                <el-dropdown-item
                  v-has="permissionTakeOrder"
                  v-if="scope.row.orderState !== 1 && scope.row.orderState !== 15 && scope.row.orderState !== 20 && !scope.row.waiterId"
                  @click.native="handleSetWaiter(scope.row)"
                >
                  设置服务员
                </el-dropdown-item>
                <el-dropdown-item
                  v-has="permissionTakeOrder"
                  v-if="scope.row.orderState >= 5 && scope.row.orderState < 15 && scope.row.waiterId && scope.row.orderType === 1"
                  @click.native="handleSetWaiter(scope.row, true)"
                >
                  服务员转单
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionQuery" v-if="scope.row.ruleId === 100 && scope.row.orderState === 20" @click.native="handleQueryResult(scope.row)"> 结果查询 </el-dropdown-item>
                <el-dropdown-item v-has="permissionModifyPrice" v-if="scope.row.orderState < 15 && !scope.row.lastAmount" @click.native="handleModifyPrice(scope.row)"> 修改价格 </el-dropdown-item>
                <el-dropdown-item v-has="permissionCancelOrder" v-if="scope.row.orderState < 15" @click.native="handleCancelOrder(scope.row)"> 取消订单 </el-dropdown-item>
                <el-dropdown-item v-has="permissionSure" v-if="scope.row.orderState < 15" @click.native="handleOrderOperation(scope.row, 10)"> 确认 </el-dropdown-item>
                <el-dropdown-item v-has="permissionDepart" v-if="isDepart(scope.row.orderState)" @click.native="handleOrderOperation(scope.row, 11)"> 出发 </el-dropdown-item>
                <el-dropdown-item v-has="permissionArrive" v-if="isArrive(scope.row.orderState)" @click.native="handleOrderOperation(scope.row, 12)"> 到达 </el-dropdown-item>

                <el-dropdown-item v-has="permissionArrive" v-if="isRecovery(scope.row)" @click.native="handleOrderOperation(scope.row, 13)"> 回收 </el-dropdown-item>

                <el-dropdown-item v-has="permissionComplete" v-if="isFinish(scope.row.orderState)" @click.native="handleOrderOperation(scope.row, 20)"> 完成 </el-dropdown-item>
                <el-dropdown-item v-has="permissionOrderCancel" v-if="scope.row.errorState === 3" @click.native="handleOrderCancel(scope.row, 1)"> 同意取消订单 </el-dropdown-item>
                <el-dropdown-item v-has="permissionOrderCancel" v-if="scope.row.errorState === 3" @click.native="handleOrderCancel(scope.row, 2)"> 拒绝取消订单 </el-dropdown-item>
                <el-dropdown-item v-has="permissionPrint" @click.native="handleOrderPrint(scope.row.orderId, true)"> 打印小票 </el-dropdown-item>

                <el-dropdown-item @click.native="rowItem = scope.row">
                  <el-upload action="#" :auto-upload="false" style="display: inline-block" :show-file-list="false" accept=".png,.jpg,.jpeg,.bmp,.gif,.webp" :on-change="handleInvoiceChange"> 上传发票 </el-upload>
                </el-dropdown-item>

                <el-dropdown-item v-has="permissionComplete" @click.native="handleCallBeeper(scope.row.orderId)"> 拨打 </el-dropdown-item>

                <el-dropdown-item v-has="permissionReleaseAlert" v-if="scope.row.orderType === 8 && scope.row.orderState < 15" @click.native="handleReleaseAlert(scope.row)"> 解除警报 </el-dropdown-item>
                <el-dropdown-item v-has="permissionCombinationOrder" v-if="scope.row.combineId" @click.native="handleCombinationOrderBtnClick(scope.row)"> 组合下单</el-dropdown-item>
                <el-dropdown-item v-has="permissionRemark" @click.native="handleAddRemark(scope.row)">添加备注</el-dropdown-item>
                <el-dropdown-item v-has="permissionUrgentContact" @click.native="handleGotoOrderUrgentContact(scope.row)">紧急联系</el-dropdown-item>
                <el-dropdown-item v-has="permissionAddToAlarmOrder" @click.native="handleAddToAlarmOrder(scope.row)">追加报警记录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <!--接单弹框  -->
    <el-dialog title="接单服务员" :visible.sync="takeOrder.show" width="463px" center>
      <div class="take-order">
        <el-input placeholder="请选择服务员" :value="takeOrder.waiterNames" :readOnly="true" @click.native="takeOrder.showWaiterList = true"> </el-input>
        <!-- <el-select
          class="item"
          v-model="waiterId"
          clearable
          placeholder="请选择服务员"
          filterable
        >
          <el-option
            v-for="item in waiterList"
            :value="item.id"
            :label="item.name"
            :key="item.id"
          >
          </el-option>
        </el-select> -->
        <el-input class="item" :rows="3" v-model="takeOrder.remark" clearable placeholder="备注" type="textarea"></el-input>
        <div class="item img-wrapper">
          <div class="img-item" v-for="(item, index) in images">
            <el-image :src="item" fit="cover" :key="index" :preview-src-list="images"></el-image>
            <i class="el-icon-circle-close" @click="handleDelImg(index)"></i>
          </div>
          <UploadImg v-show="limit >= 1" class="upload-img" folder="order/img" @uploadFileList="images = images.concat($event)" :limit="limit"></UploadImg>
        </div>
      </div>

      <span slot="footer">
        <el-button @click="takeOrder.show = false">取 消</el-button>
        <el-button type="primary" @click="sureTakeOrder()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog append-to-body :visible.sync="takeOrder.showWaiterList" title="选择服务员" center width="fit-content">
      <el-table ref="tableRef" @row-click="$refs.tableRef.toggleRowSelection($event)" @selection-change="handleSelectWaiter" :data="waiterList" max-height="400">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column label="姓名" prop="fullName" width="150" align="center"></el-table-column>
        <el-table-column label="昵称" prop="name" width="150" align="center"></el-table-column>
        <el-table-column label="接单数量" prop="orderNum" width="100" align="center"></el-table-column>
        <el-table-column label="接单方式" width="120" align="center">
          <template slot-scope="{ row: { takeOrdersWay } }">
            <el-tag size="mini" :type="takeOrdersWay === 1 ? 'error' : 'success'">
              {{ takeOrdersWay === 1 ? '手动接单' : '自动接单' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上班状态" width="150" align="center">
          <template slot-scope="{ row: { timing } }">
            {{ formatTiming(timing) }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button type="primary" @click="confirmSelectWaiters">确定选择</el-button>
        <el-button @click="takeOrder.showWaiterList = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 完成或者回收弹框 -->
    <el-dialog title="选择上传图片" :visible.sync="finishDialog" width="470px" center>
      <div class="item img-wrapper">
        <div class="img-item" v-for="(item, index) in images">
          <el-image :src="item" fit="cover" :key="index" :preview-src-list="images"></el-image>
          <i class="el-icon-circle-close" @click="handleDelImg(index)"></i>
        </div>
        <UploadImg v-show="limit >= 1" class="upload-img" folder="order/img" @uploadFileList="images = images.concat($event)" :limit="limit"></UploadImg>
      </div>
      <span slot="footer">
        <el-button @click="finishDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleOrderOperation(0, state, true)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 取消订单弹框 -->
    <el-dialog title="取消原因" :visible.sync="cancelOrderDialog" width="350px" center>
      <div style="color: red; margin-bottom: 4px">已与客户沟通，同意取消订单</div>
      <el-input type="textarea" placeholder="请输入取消订单的原因" :rows="5" v-model="cancelReason"></el-input>
      <span slot="footer">
        <el-button @click="cancelOrderDialog = false">取 消</el-button>
        <el-button type="primary" @click="sureCancelOrder()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 改价弹框 -->
    <el-dialog title="修改价格" :visible.sync="modifyPriceDialog" width="400px" center class="modify-price">
      <el-row>
        <el-col :span="6">服务名称：</el-col>
        <el-col :span="12">{{ modifyPriceForm.serverName }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="6">价格：</el-col>
        <el-col :span="12">{{ modifyPriceForm.realAmount }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="6">改价为：</el-col>
        <el-col :span="12">
          <el-input type="number" v-model.number.trim="modifyPriceForm.modifyPrice" @input="handlePriceInput"> </el-input>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">改价备注：</el-col>
        <el-col :span="12">
          <el-input type="textarea" style="font-size: 14px" size="mini" v-model="modifyPriceForm.remark"></el-input>
        </el-col>
      </el-row>
      <span slot="footer">
        <el-button @click="modifyPriceDialog = false">取 消</el-button>
        <el-button type="primary" @click="sureModifyPrice">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 操作记录列表 -->
    <el-dialog title="操作记录" :visible.sync="operationRecordDialog" center width="max-content">
      <el-table :data="operationRecordList">
        <el-table-column label="人员类型" align="center" width="120px">
          <template slot-scope="scope">
            {{ formatOperatorType(scope.row.operatorType) }}
          </template>
        </el-table-column>
        <el-table-column label="具体操作" prop="operation" align="center" width="150px"> </el-table-column>
        <el-table-column label="操作日期" prop="operationDate" align="center" width="150px"> </el-table-column>
        <el-table-column label="操作备注" prop="remark" align="center" width="200px"> </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 设置服务员 -->
    <el-dialog :title="transferOrder ? '服务员转单' : '设置服务员'" :visible.sync="setWaiterDialog" width="350px" center>
      <el-select style="width: 100%; margin-bottom: 10px" v-model="waiterId" clearable placeholder="请选择服务员" filterable>
        <el-option v-for="item in waiterList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
      </el-select>
      <span slot="footer">
        <el-button @click="setWaiterDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmSetWaiter()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 导出结算记录 -->
    <el-dialog title="选择时间" :visible.sync="settleRecord.show" center width="fit-content" class="custom-size__dialog">
      <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" v-model="settleRecord.time" start-placeholder="开始时间" end-placeholder="结束时间"> </el-date-picker>
      <div slot="footer">
        <el-button type="primary" @click="confirmExportSR"> 确定 </el-button>
        <el-button @click="settleRecord.show = false"> 取消 </el-button>
      </div>
    </el-dialog>

    <!-- 打印提示弹框 -->
    <el-dialog title="打印提示" :visible.sync="print.show" center width="fit-content">
      <div class="flex-box">
        <div class="item">
          <div class="label"><i class="el-icon-success" style="color: #67c23a; margin-right: 4px"></i>成功次数:</div>
          <div class="value">{{ print.printSucceed }}</div>
        </div>
        <div class="item">
          <div class="label"><i class="el-icon-warning" style="color: #f56c6c; margin-right: 4px"></i>失败次数:</div>
          <div class="value">{{ print.printFail }}</div>
        </div>
        <div class="item">
          <div class="label"><i class="el-icon-info" style="color: #409eff; margin-right: 4px"></i>打印中:</div>
          <div class="value">{{ print.printing }}</div>
        </div>
        <div class="item">
          <div class="label"><i class="el-icon-info" style="color: #409eff; margin-right: 4px"></i>调用失败:</div>
          <div class="value">{{ print.printError }}</div>
        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="handleOrderPrint()"> 确定打印 </el-button>
        <el-button @click="print.show = false"> 取消 </el-button>
      </div>
    </el-dialog>

    <el-dialog title="转单记录" center :visible.sync="transferOrderRecord.show" width="fit-content">
      <el-table :data="transferOrderRecord.list">
        <el-table-column label="序号" type="index" align="center" width="120"></el-table-column>
        <el-table-column label="转单服务员" prop="waiterName" align="center" width="140"></el-table-column>
        <el-table-column label="转单进度" align="center" width="140">
          <template slot-scope="scope">
            <el-tag size="mini" effect="dark" style="border: none" :color="formatOrderStates(scope.row.waiterProgress)">
              {{ formatOrderState(scope.row.waiterProgress) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="当前服务员" prop="nowWaiterName" align="center" width="140"></el-table-column>

        <el-table-column label="转单时间" prop="createDate" width="160" align="center"></el-table-column>
        <el-table-column label="操作人" prop="createUserName" width="160" align="center"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 上传发票 -->
    <el-dialog :visible.sync="invoice.show" title="上传发票" center width="fit-content">
      <el-image style="width: 400px; height: 400px" fit="scale-down" :src="invoice.blobUrl" :preview-src-list="[invoice.blobUrl]"> </el-image>

      <div slot="footer">
        <el-button type="primary" :icon="invoice.uploadLoading ? 'el-icon-loading' : 'el-icon-upload'" @click="confirmUploadInvoice">{{ invoice.uploadLoading ? '上传中' : '上传' }}</el-button>
      </div>
    </el-dialog>

    <!-- 误触 or 已处理  -->
    <el-dialog title="提示" width="400px" :visible.sync="dialogAlertVisible">
      确定解除警报吗？
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogAlertVisible = false">关闭弹窗</el-button>
        <el-button size="mini" type="warning" @click="handleReleaseAlertLogic(1)">误触发</el-button>
        <el-button size="mini" type="primary" @click="handleReleaseAlertLogic(2)">已处理</el-button>
      </div>
    </el-dialog>

    <!-- 组合下单 -->
    <el-dialog :visible.sync="combinationOrder.show" title="组合下单" center width="670px">
      <el-table :data="combinationOrder.table" highlight-current-row v-loading="combinationOrder.loading" @selection-change="handleCombinationOrderTableSelectionChange">
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column label="产品名称" prop="name" align="center"></el-table-column>
        <el-table-column label="商户" prop="businessName" align="center"></el-table-column>
      </el-table>
      <div slot="footer">
        <el-button type="primary" size="small" @click="handleCombinationOrderSubmit">确定</el-button>
        <el-button size="small" @click="combinationOrder.show = false"> 取消 </el-button>
      </div>
    </el-dialog>

    <!-- 添加备注 -->
    <el-dialog :visible.sync="remarkShow" title="添加备注" center width="670px">
      <div>
        <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="remarkVal"></el-input>
      </div>
      <div slot="footer">
        <el-button type="primary" size="small" @click="remarkClick(1)">确定</el-button>
        <el-button size="small" @click="remarkClick(2)"> 取消 </el-button>
      </div>
    </el-dialog>

    <!-- 追加报警订单 -->
    <el-dialog :visible.sync="addToShow" title="追加报警订单" center width="670px">
      <div style="color: red">注：请确定是否已拨打报警电话</div>
      <br />
      <div>
        <el-select v-model="alarmType" clearable placeholder="请选择报警类型">
          <el-option label="120急救" value="120"> </el-option>
          <el-option label="110报警" value="110"> </el-option>
          <el-option label="119报警" value="119"> </el-option>
        </el-select>
      </div>
      <div slot="footer">
        <el-button type="primary" size="small" @click="addToConfirm">确定</el-button>
        <el-button size="small" @click="addToCancel"> 取消 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import OrderApi from '@/api/order/order';
import OrderSplitApi from '@/api/account/orderSplit.js';
import CombineApi from '@/api/goods/combine';
import WaiterApi from '@/api/business/waiter';
import BusinessApi from '@/api/business/business';
import { getStorage } from '@/utils/auth';
import { USER_INFO } from '@/constants/storeName';
import BeeperApi from '../../api/equip/beeper';
import fileDownload from 'js-file-download';
import mixins from '@/mixins/mixins';
import UploadImg from '../../components/UploadImg.vue';
import uploadFile from '@/utils/uploadOssFn';
import PriceRange from '../../components/PriceRange.vue';
import { alarmOrderTypeList, alarmOrderSourceList, EAlarmTypeList } from '../../enum';
export default {
  name: 'AlarmOrderManagement',
  inject: ['reload'], //注入局部刷新
  mixins: [mixins],
  data() {
    return {
      alarmType: '',
      userRole: '',
      detailRole: '',
      relationRoleId: '',
      setWaiterDialog: false,
      // takeOrderDialog: false, //接单弹框
      cancelOrderDialog: false, //取消订单的弹框
      operationRecordDialog: false,
      orderId: '', //选择一行保存的订单id，
      waiterId: '', //选择的服务员
      takeOrder: {
        show: false, //显示接单弹框
        showWaiterList: false, //显示服务员列表
        power: 0,
        waiterIds: [],
        waiterNames: '',
        selectedWaiters: [],
        remark: '',
      },
      selectForm: {
        ids: [],
        state: '',
      },
      transferOrder: false,
      transferOrderRecord: {
        show: false,
        list: [],
      },
      images: [], //需要上传的图片列表
      // remark: "", //接单备注
      finishDialog: false, //完成弹框
      cancelReason: '', //取消订单的原因
      waiterList: [], //服务员列表
      modifyPriceDialog: false, //修改价格弹框
      modifyPriceForm: {
        serverName: '',
        realAmount: '',
        modifyPrice: '',
        remark: '',
      },
      operationRecordList: [], //操作订单列表
      dataList: [],
      beeperList: [],
      listLoading: true,
      filters: {
        orderNo: '',
        orderType: '',
        beeperId: '',
        businessId: '',
        classifyName: '',
        alarmType: '',
        fastFlag: '',
        orderState: '',
        errorState: '',
        payType: '',
        // realAmountMin: "",
        payState: '',
        date: [],
        dateType: 1,
        goodsName: '',
        orderSource: '',
        priceRange: [],
        serverClassifyIds: '',
        originNo: '',
      },
      alarmOrderTypeList,
      alarmOrderSourceList,
      EAlarmTypeList,
      orderStateList: [
        { value: 1, label: '待接单' },
        { value: 5, label: '已接单' },
        { value: 10, label: '已确认' },
        { value: 11, label: '已出发' },
        { value: 12, label: '已到达' },
        { value: 13, label: '已回收' },
        { value: 15, label: '已取消' },
        { value: 16, label: '取消失败' },
        { value: 20, label: '已完成' },
      ],
      payTypeList: [
        { value: 1, label: '余额' },
        { value: 2, label: '微信支付' },
        { value: 3, label: '货到付款' },
        { value: 4, label: '他人代付' },
        { value: 5, label: '0元购' },
      ],
      payStateList: [
        { value: 1, label: '未支付' },
        { value: 4, label: '未支付差价' },
        { value: 5, label: '已支付' },
        { value: 10, label: '已取消' },
        { value: 15, label: '已退款' },
        { value: 20, label: '完成' },
      ],
      errorStateList: [
        { value: 1, label: '超时未接单' },
        { value: 2, label: '商户取消' },
        { value: 3, label: '用户申请取消' },
      ],
      formatOperatorType(cellValue) {
        if (cellValue === 1) {
          return '管理员';
        } else if (cellValue === 2) {
          return '客户';
        } else if (cellValue === 3) {
          return '商户';
        } else if (cellValue === 4) {
          return '服务员';
        } else if (cellValue === 20) {
          return '客服';
        }
      },
      businessList: [],
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 10,
      },

      permissionAdd: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_ADD',
      permissionExport: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_EXPORT',
      permissionCheck: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_SEE',
      permissionOperationRecord: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_OPERATERECORD',
      permissionModifyPrice: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_MODIFYPRICE',
      permissionTakeOrder: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_TAKEORDER',
      permissionDelOrder: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_DELORDER',
      permissionCancelOrder: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_CANCELORDER',
      permissionSure: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_SURE',
      permissionDepart: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_DEPART',
      permissionArrive: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_ARRIVE',
      permissionComplete: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_COMPLETE',
      permissionScreen: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_SCREEN',
      permissionPrint: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_PRINT',
      permissionOrderCancel: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_ORDERCANCEL',
      permissionSettleRecord: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_SETTLE_RECORD',
      permissionQuery: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_QUERY',
      permissionTransferOrder: 'SYSTEM_MANAGER_ORDER_ARARMINFO_LIST_TRANSFERORDER',
      permissionCombinationOrder: 'SYSTEM_MANAGER_ORDER_ARARMINFO_COMBINATION_ORDER',
      permissionReleaseAlert: 'SYSTEM_MANAGER_ORDER_ARARMINFO_RELEASE_ALERT',
      permissionReset: 'SYSTEM_MANAGER_ORDER_ARARMINFO_RESET',
      permissionRemark: 'SYSTEM_MANAGER_ORDER_ARARMINFO_REMARK',
      permissionUrgentContact: 'SYSTEM_MANAGER_ORDER_ARARMINFO_URGENT_CONTACT',
      permissionAddToAlarmOrder: 'SYSTEM_MANAGER_ORDER_ARARMINFO_ADDTO_ALARM_ORDER',
      colorContainer: [
        //标签中的颜色
        '#F56C6C',
        '#67C23A',
        '#E3EA11',
        '#11C6EA',
        '#909399',
        '#595E8C',
        '#409EFF',
        '#EF5110',
        '#F71254',
        '#CCA2AE',
        '#2E34C7',
        '#2970CE',
        '#8728D7',
        '#19CBCD',
        '#407474',
      ],
      setWaiter: {
        show: false,
        waiterId: '',
      },
      settleRecord: {
        show: false,
        time: null,
      },
      print: {
        show: false,
        printFail: '',
        printSucceed: '',
        printing: '',
        printError: '',
      },
      state: '',
      invoice: {
        blobUrl: '',
        show: false,
        file: '',
        uploadLoading: false,
      },
      rowItem: {},
      dialogAlertVisible: false,
      alertOrders: undefined,
      combinationOrder: {
        show: false,
        loading: false,
        selected: [],
        orderId: undefined,
        table: [],
      },
      remarkShow: false,
      remarkVal: '',
      addToShow: false,
    };
  },
  components: {
    UploadImg,
    PriceRange,
  },
  computed: {
    limit() {
      return 5 - this.images.length;
    },
  },
  // beforeRouteEnter (to, from, next) {
  //   console.log(to.path,from.path)
  //   next()
  // },
  mounted() {
    const { serverClassifyIds } = this.$route.query;
    if (serverClassifyIds) {
      this.filters.serverClassifyIds = serverClassifyIds;
    }
    this.init();
    // window.addEventListener("keydown", this.keyDown);
  },
  activated() {
    if (this.$route.params.safetyEquipIds) {
      this.pageNo = 1;
      this.listData();
    }
  },
  watch: {},
  methods: {
    init() {
      // 获取用户的角色信息
      this.userRole = getStorage(USER_INFO).userRole;
      this.detailRole = getStorage(USER_INFO).detailRole;
      this.relationRoleId = getStorage(USER_INFO).relationRoleId;
      this.listLoading = true;
      if (this.$route.query.orderState || this.$route.query.today) {
        this.filters.orderState = this.$route.query.orderState;
        this.initDate();
      }

      this.listData();
      this.listBeeper();
      // _this.getTableHeight();
      this.getBusinessList();
    },
    handleAddToAlarmOrder(row) {
      this.orderId = row.orderId;
      this.addToShow = true;
    },
    initDate() {
      let begin = new Date();
      begin.setHours(0);
      begin.setMinutes(0);
      begin.setSeconds(0);
      // begin.setMonth(begin.getMonth());
      let end = new Date();
      end.getHours();
      end.getMinutes();
      end.getSeconds();
      this.filters.date = [begin, end];
    },
    // 获取图片
    getImgList(val) {
      this.images = this.images.concat(val);
    },
    // 删除图片
    handleDelImg(index) {
      this.images.splice(index, 1);
    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo({}).then((res) => {
        this.businessList = res.data;
      });
    },
    toLargeScreen() {
      window.open(`https://bigscreen.kanglailab.com/#/view/1749834129480597505?tenantId=${this.$store.getters.tenantId}`);
    },
    formatTiming(time) {
      if (time) {
        const hours = Math.floor(time / 60);
        const minutes = time % 60;
        time = hours ? hours + '小时' : '';
        time = minutes ? time + (minutes + '分钟') : time;
        if (hours > 0 || minutes > 0) {
          return '已经下班' + time;
        } else if (hours < 0 || minutes < 0) {
          return '距离下班' + time;
        }
      }
    },
    // 判断是否出发
    isDepart(state) {
      return state === 5 || state === 10;
    },
    // 判断是否显示到达
    isArrive(state) {
      return state === 5 || state === 10 || state === 11;
    },
    // 判断是否显示回收
    isRecovery(row) {
      return row.orderState === 12 && row.orderType === 3 && (row.timingState === 2 || row.timingState === 3);
    },
    // 判断是否显示完成
    isFinish(state) {
      return state === 5 || state === 10 || state === 11 || state === 12;
    },
    // 打印小票
    async handleOrderPrint(id) {
      const { print } = this;
      if (id) {
        const res = await OrderApi.printStatistics({ orderId: id });
        if (res.data) {
          this.$Utils.bindingBean(print, res.data);
          this.orderId = id;
          print.show = true;
          return;
        }
      }
      if (id) {
        await this.$confirm('确定打印小票吗？', '提示', {});
      }

      try {
        await OrderApi.orderPrint({ id: id || this.orderId });
        this.$Utils.notifySuccess();
      } finally {
        print.show = false;
      }
    },
    handleTimeType(val) {
      this.filters.dateType = val;
    },
    handleSelectionChange(value) {
      this.selectForm.ids = value.map((item) => item.orderId);
    },
    // 获取转单记录
    async getTransferOrderRecord(row) {
      const { data } = await OrderApi.listTransferRecord({
        orderId: row.orderId,
      });
      this.transferOrderRecord.list = data || [];
      this.transferOrderRecord.show = true;
    },
    // 随机获取颜色
    tagsSetColor() {
      this.dataList.forEach((item) => {
        if (item.tags) {
          let arr = item.tags.split(',');
          let length = this.colorContainer.length;
          item.tags = [];
          arr.forEach((item2) => {
            let color = this.colorContainer[Math.floor(Math.random() * length)];
            item.tags.push({ tagName: item2, color: color });
          });
        }
        if (item.orderTag) {
          let arr = item.orderTag.split(',');
          item.orderTag = [];
          arr.forEach((item2) => {
            if (item2 === 1) {
              item.orderTag.push({ tagName: '新', color: '#16DE12' });
            } else if (item2 === 2) {
              item.orderTag.push({ tagName: '急', color: '#EB3F25' });
            }
          });
        }
      });
    },
    // 上传发票
    handleInvoiceChange(file) {
      this.invoice.file = file;
      this.invoice.blobUrl = window.URL.createObjectURL(file.raw);
      this.invoice.show = true;
    },
    // 确认上传发票
    async confirmUploadInvoice() {
      if (this.invoice.uploadLoading) return;
      this.invoice.uploadLoading = true;
      try {
        const res = await uploadFile([this.invoice.file], 'invoice');
        await OrderApi.setInvoice({ id: this.rowItem.orderId, value: res[0].url });
        this.invoice.show = false;
      } finally {
        this.invoice.uploadLoading = false;
      }
    },
    formatFastFlag(cellValue) {
      if (cellValue === 1) {
        return '急';
      } else if (cellValue === 0) {
        return '';
      }
    },
    formatOrderType(cellValue) {
      if (cellValue === 1) {
        return '普通订单';
      } else if (cellValue === 3) {
        return '计时';
      } else if (cellValue === 8) {
        return '报警';
      } else if (cellValue === 9) {
        return '语音单';
      } else if (cellValue === 10) {
        return '补贴';
      } else if (cellValue === 11) {
        return '急救订单';
      }
    },
    formatOrderTypes(cellValue) {
      if (cellValue === 1) {
        return '';
      } else if (cellValue === 3) {
        return 'warning';
      } else if (cellValue === 8) {
        return 'danger';
      } else if (cellValue === 9) {
        return 'success';
      } else if (cellValue === 11) {
        return 'error';
      }
    },
    formatOrderState(cellValue) {
      if (cellValue === 1) {
        return '已接单待确认';
      } else if (cellValue === 5) {
        return '商户已确认';
      } else if (cellValue === 10) {
        return '服务员已确认';
      } else if (cellValue === 11) {
        return '已出发';
      } else if (cellValue === 12) {
        return '已到达';
      } else if (cellValue === 13) {
        return '已回收';
      } else if (cellValue === 15) {
        return '已取消';
      } else if (cellValue === 16) {
        return '取消失败';
      } else if (cellValue === 20) {
        return '已完成';
      }
    },

    formatOrderStates(cellValue) {
      if (cellValue === 1) {
        return '#F56C6C';
      } else if (cellValue === 5) {
        return '#67C23A';
      } else if (cellValue === 10) {
        return '#E3EA11';
      } else if (cellValue === 11) {
        return '#11C6EA';
      } else if (cellValue === 12) {
        return '#6B8D9D';
      } else if (cellValue === 13) {
        return '#8B8D9D';
      } else if (cellValue === 15) {
        return '#909399';
      } else if (cellValue === 16) {
        return '#595E8C';
      } else if (cellValue === 20) {
        return '#409EFF';
      }
    },
    formatPayType(cellValue) {
      if (cellValue === 1) {
        return '余额';
      } else if (cellValue === 2) {
        return '微信支付';
      } else if (cellValue === 3) {
        return '货到付款';
      } else if (cellValue === 4) {
        return '他人代付';
      } else if (cellValue === 5) {
        return '0元购';
      } else if (cellValue === 6) {
        return '线下月结';
      } else if (cellValue === 7) {
        return '线下余额';
      }
    },
    formatPayState(cellValue) {
      if (cellValue === 1) {
        return '未支付';
      } else if (cellValue === 4) {
        return '未支付差价';
      } else if (cellValue === 5) {
        return '已支付';
      } else if (cellValue === 10) {
        return '已取消';
      } else if (cellValue === 15) {
        return '已退款';
      } else if (cellValue === 20) {
        return '完成';
      }
    },

    formatPayStates(cellValue) {
      if (cellValue === 1) {
        return 'danger';
      } else if (cellValue === 4) {
        return 'danger';
      } else if (cellValue === 5) {
        return 'success';
      } else if (cellValue === 10) {
        return 'info';
      } else if (cellValue === 15) {
        return 'warning';
      } else if (cellValue === 20) {
        return '';
      }
    },
    formatPrintState(cellValue) {
      if (cellValue === 0) {
        return '待打印';
      } else if (cellValue === 1) {
        return '打印中';
      } else if (cellValue === 2) {
        return '打印成功';
      } else if (cellValue === 3) {
        return '打印失败';
      } else if (cellValue === 4) {
        return '打印已取消';
      } else if (cellValue === 5) {
        return '调用失败';
      }
    },

    formatPrintStates(cellValue) {
      if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return '';
      } else if (cellValue === 2) {
        return 'success';
      } else if (cellValue === 3) {
        return 'danger';
      } else if (cellValue === 4) {
        return 'info';
      } else if (cellValue === 5) {
        return 'warning';
      }
    },
    // getTableHeight() {
    //   this.$nextTick(function () {
    //     this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
    //     window.onresize = () => {
    //       this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
    //     }
    //   })
    // },
    handleClickAdd() {
      this.$router.push('/order/orderAdd');
    },
    handleClickBatchOperate(state) {
      // 批量操作订单
      if (this.selectForm.ids.length === 0) {
        this.$message.error('至少选择一项数据');
        return false;
      }
      var cond = {
        ids: this.selectForm.ids,
        state: state,
      };
      this.$confirm(`确定完成${this.selectForm.ids.length}笔订单么？`, '提示', {}).then((res) => {
        OrderApi.orderBatchOperate(cond).then((data) => {
          this.$Utils.notifySuccess();
          this.listData();
        });
      });
    },
    handleExport() {
      if (this.page.pageTotal > 1000) {
        this.$message.error('订单数量超过1000条，请选择下单时间分批导出');
        return false;
      }
      let params = {
        orderNo: this.filters.orderNo,
        orderType: this.filters.orderType,
        beeperId: this.filters.beeperId,
        businessId: this.filters.businessId,
        orderState: this.filters.orderState,
        errorState: this.filters.errorState,
        payType: this.filters.payType,
        payState: this.filters.payState,
        dateType: this.filters.dateType,
        goodsName: this.filters.goodsName,
        orderSource: this.filters.orderSource,
        alarmType: this.filters.alarmType,
        originNo: this.filters.originNo,
        typesQuery: 2,
      };
      if (this.filters.date.length > 0) {
        params.beginDate = this.$Utils.formatDate(this.filters.date[0], 'yyyy-MM-dd hh:mm:ss');
        params.endDate = this.$Utils.formatDate(this.filters.date[1], 'yyyy-MM-dd hh:mm:ss');
      }
      OrderApi.exportOrder(params).then((res) => {
        this.$Utils.notifySuccess('导出成功');
        fileDownload(res, '订单列表.xlsx');
      });
    },
    // 导出结算记录
    handleExportSR() {
      const { settleRecord } = this;
      settleRecord.show = true;
    },
    confirmExportSR() {
      const { settleRecord } = this;
      const { time } = settleRecord;
      const params = {
        beginDate: time ? time[0] : '',
        endDate: time ? time[1] : '',
      };
      let loading = this.$loading({
        lock: true,
        text: '导出中',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      OrderApi.exportSettle(params)
        .then((res) => {
          fileDownload(res, '结算记录.xlsx');
        })
        .finally(() => {
          settleRecord.show = false;
          loading.close();
        });
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/order/orderDetail',
        query: { id: row.orderId },
      });
    },
    handleGotoOrderUrgentContact(row) {
      let _this = this;
      _this.$router.push({
        path: '/order/OrderUrgentContact',
        query: { id: row.orderId },
      });
    },

    // 操作记录
    handleOperationRecord(row) {
      this.orderId = row.orderId;
      OrderApi.orderOperationRecord({ orderId: this.orderId }).then((res) => {
        this.operationRecordList = res.data;
        this.operationRecordDialog = true;
      });
    },

    //删除订单
    handleDelOrder(row) {
      this.$confirm('是否确定删除该订单', '提示', {}).then((res) => {
        OrderApi.delOrder({ id: row.orderId }).then((data) => {
          if (data.status === 0) {
            this.$message.success('操作成功');
            this.listData();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    // 设置服务员
    handleSetWaiter(row, transferOrder) {
      this.transferOrder = transferOrder;
      this.orderId = row.orderId;
      this.waiterId = row.waiterId || '';
      this.remark = '';
      const params = {
        businessId: row.businessId,
        departId: row.departId || '',
        firstDepartId: row.firstDepartId || '',
        secondDepartId: row.secondDepartId || '',
        thirdDepartId: row.thirdDepartId || '',
        orderId: row.orderId,
      };
      this.listWaiter(params);
      this.setWaiterDialog = true;
    },
    // 确认设置服务员
    async confirmSetWaiter() {
      const param = {
        orderId: this.orderId,
        waiterId: this.waiterId,
      };
      if (this.transferOrder) {
        await OrderApi.transfersOrder(param);
        this.$Utils.notifySuccess('转单成功');
      } else {
        await OrderApi.setWaiter(param);
        this.$Utils.notifySuccess('设置成功');
      }

      this.listData();
      this.setWaiterDialog = false;
    },
    // 查询结果
    async handleQueryResult(row) {
      const { data } = await OrderApi.listKlabReportUrl({
        orderId: row.orderId,
      });
      if (!data) {
        this.$message.error('暂无查询结果');
        return;
      }
      const a = document.createElement('a');
      a.target = '_blank';
      a.href = data;
      a.click();
    },
    // 重置订单分账
    async handleResetSplitOrder() {
      if (this.selectForm.ids.length === 0) {
        this.$message.error('至少选择一项数据');
        return false;
      }

      await this.$confirm('确定重置订单分账吗？', '提示', {});
      const params = {
        state: 1,
        ids: this.selectForm.ids,
      };
      await OrderSplitApi.resetSplit(params);
      this.onSearch();
      this.$Utils.notifySuccess();
    },
    // 处理点击接单
    handleTakeOrder(row) {
      this.orderId = row.orderId;
      // this.businessId = row.businessId
      this.takeOrder.waiterIds = [];
      this.takeOrder.waiterNames = '';
      this.takeOrder.remark = '';
      this.takeOrder.images = [];
      const params = {
        businessId: row.businessId,
        departId: row.departId || '',
        firstDepartId: row.firstDepartId || '',
        secondDepartId: row.secondDepartId || '',
        thirdDepartId: row.thirdDepartId || '',
        orderId: row.orderId,
        waiterType: row.waiterRestrict,
        limitNo: 5,
      };
      this.listWaiter(params);
      this.takeOrder.show = true;
    },
    handleCallBeeper(orderId) {
      let phone = this.filters.orderNo;
      OrderApi.callBeeper({ orderId: orderId, phone: phone }).then((res) => {
        this.$Utils.notifySuccess();
      });
    },
    handleSelectWaiter(val) {
      const { takeOrder, waiterList } = this;
      const target = val.find((item) => item.takeOrdersWay === 2);
      if (target && val.length > 1) {
        if (waiterList.length === val.length) {
          this.$refs.tableRef.clearSelection();
        } else {
          this.$refs.tableRef.toggleRowSelection(val.at(-1), false);
        }
        return this.$message.error('自动接单只能选择一个服务员');
      }
      takeOrder.selectedWaiters = val;
    },
    async confirmSelectWaiters() {
      const { takeOrder } = this;
      if (!takeOrder.selectedWaiters.length) {
        return this.$message.error('请选择一个服务员');
      }

      try {
        if (takeOrder.selectedWaiters.length === 1 && takeOrder.selectedWaiters[0].takeOrdersWay === 1) {
          await this.$confirm('确定指派该服务员接单吗？', '提示');
          takeOrder.power = 1;
        }
      } catch (err) {
        takeOrder.power = 0;
      } finally {
        takeOrder.waiterIds = takeOrder.selectedWaiters.map((item) => item.id);
        takeOrder.waiterNames = takeOrder.selectedWaiters.map((item) => item.name).join(',');
        takeOrder.showWaiterList = false;
      }
    },
    // 确认接单
    sureTakeOrder() {
      const { waiterIds, remark, images, power } = this.takeOrder;
      let param = {
        orderId: this.orderId,
        waiterIds,
        remark,
        images,
        power,
        // business:this.businessId,
      };
      const loading = this.$loading({
        text: '正在处理...',
      });
      OrderApi.takeOrder(param)
        .then((res) => {
          this.listData();
          this.takeOrder.show = false;
          this.$Utils.notifySuccess();
        })
        .finally(() => {
          loading.close();
        });
    },

    // 处理点击取消订单
    handleCancelOrder(row) {
      this.orderId = row.orderId;
      this.cancelReason = '';
      this.cancelOrderDialog = true;
    },
    // 确认取消接单
    sureCancelOrder() {
      if (!this.cancelReason) {
        this.$message('请填写取消接单的原因');
        return;
      }
      let param = {
        orderId: this.orderId,
        cancelReason: this.cancelReason,
      };
      OrderApi.cancelOrder(param).then((res) => {
        this.cancelOrderDialog = false;
        this.listData();
        this.$Utils.notifySuccess();
      });
    },
    // 处理订单确认、出发、到达、完成
    handleOrderOperation(row, state, finish) {
      const { orderId, images } = this;
      let loading = '';
      if (!finish && (state === 20 || state === 13)) {
        this.finishDialog = true;
        this.orderId = row.orderId;
        this.state = state;
        this.images = [];
        return;
      }

      let params = {
        id: row ? row.orderId : orderId,
        state,
      };
      if (state === 20 || state === 13) {
        params.images = images;
        loading = this.$loading({
          text: '提交中...',
        });
      }

      OrderApi.orderOperate(params)
        .then((res) => {
          this.listData();
          this.finishDialog = false;
          this.$Utils.notifySuccess();
        })
        .finally(() => {
          if (loading) {
            loading.close();
          }
        });
    },
    // 是否同意取消订单
    handleOrderCancel(row, state) {
      let params = {
        id: row.orderId,
        state,
      };
      this.$confirm(state === 1 ? '确定同意取消订单？' : '确定拒绝取消订单？', '提示', {}).then(() => {
        OrderApi.affirmOrder(params).then((res) => {
          this.listData();
          this.$Utils.notifySuccess();
        });
      });
    },
    // 订单修改价格
    handleModifyPrice(row) {
      this.modifyPriceDialog = true;
      this.modifyPriceForm.serverName = row.serverName;
      this.modifyPriceForm.realAmount = row.realAmount;
      this.modifyPriceForm.modifyPrice = '';
      this.orderId = row.orderId;
      this.modifyPriceForm.remark = '';
    },
    // 价格输入
    handlePriceInput() {
      if (this.modifyPriceForm.modifyPrice < 0) {
        this.modifyPriceForm.modifyPrice = '';
      }
    },
    // 确认订单修改价格
    sureModifyPrice() {
      let cond = {
        orderId: this.orderId,
        oldPrice: this.modifyPriceForm.realAmount,
        price: this.modifyPriceForm.modifyPrice,
        remark: this.modifyPriceForm.remark,
      };
      if (!cond.price) {
        this.$message.error('请输入改价金额');
        return;
      }
      if (!cond.remark) {
        this.$message.error('请输入改价备注');
        return;
      }
      OrderApi.orderChangePrice(cond).then((res) => {
        this.listData();
        this.modifyPriceDialog = false;
        this.$message.success('修改成功');
      });
    },

    resetForm() {
      this.filters.dateType = 1;
      this.$refs.searchForm.resetFields();
      this.$route.params.safetyEquipIds = '';
      this.onSearch();
    },
    onSearch() {
      this.listLoading = true;
      this.page.pageNo = 1;
      this.listData();
    },
    // 获取当前商户的服务员列表
    listWaiter({ businessId, departId, firstDepartId, secondDepartId, thirdDepartId, orderId, waiterType }) {
      const params = {
        businessId,
        departId: departId,
        firstDepartId: firstDepartId,
        secondDepartId: secondDepartId,
        thirdDepartId: thirdDepartId,
        orderId,
        waiterType,
      };
      WaiterApi.listIdName(params).then((res) => {
        this.waiterList = res.data || [];
      });
    },
    listBeeper() {
      BeeperApi.beeperList().then((res) => {
        this.beeperList = res.data;
      });
    },
    listData() {
      // 获取列表数据
      let _this = this;
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
      };
      cond.orderNo = _this.filters.orderNo;
      cond.orderType = _this.filters.orderType;
      cond.typesQuery = '2';
      cond.beeperId = _this.filters.beeperId;
      cond.businessId = _this.filters.businessId;
      cond.classifyName = _this.filters.classifyName;
      cond.fastFlag = _this.filters.fastFlag;
      cond.orderState = _this.filters.orderState;
      cond.errorState = _this.filters.errorState;
      cond.payType = _this.filters.payType;
      cond.payState = _this.filters.payState;
      cond.dateType = _this.filters.dateType;
      cond.goodsName = _this.filters.goodsName;
      cond.orderSource = _this.filters.orderSource;
      cond.realAmountMin = _this.filters.priceRange[0] || '';
      cond.realAmountMax = _this.filters.priceRange[1] || '';
      cond.serverClassifyIds = _this.filters.serverClassifyIds;
      cond.originNo = _this.filters.originNo;
      cond.alarmType = _this.filters.alarmType;

      if (this.$route.params.safetyEquipIds) {
        cond.safetyEquipIds = this.$route.params.safetyEquipIds;
      }

      if (_this.filters.date && _this.filters.date.length > 0) {
        cond.beginDate = _this.$Utils.formatDate(this.filters.date[0], 'yyyy-MM-dd hh:mm:ss');
        cond.endDate = this.$Utils.formatDate(this.filters.date[1], 'yyyy-MM-dd hh:mm:ss');
        this.$Utils.formatDate(this.filters.date[0], 'yyyy-MM-dd hh:mm:ss');
      }

      OrderApi.listOrder(cond)
        .then((res) => {
          _this.dataList = res.data.list;
          _this.page.pageTotal = res.data.total;
          _this.$refs.table.bodyWrapper.scrollTop = 0;
          _this.listLoading = false;

          // 每次获取数据都重新设置标签颜色
          _this.tagsSetColor();
        })
        .catch((err) => {
          _this.listLoading = false;
        });
    },

    /**
     * 解除警报 弹出提示框
     * @param order
     */
    handleReleaseAlert(order) {
      this.dialogAlertVisible = true;
      this.alertOrders = order;
    },

    /**
     * 处理解除警报 误触 和 处理
     * @param cancelReason
     */
    handleReleaseAlertLogic(cancelReason) {
      OrderApi.orderCancelAlarm({ orderId: this.alertOrders.orderId, cancelReason }).then(() => {
        this.$message.success('解除成功');
        this.alertOrders = undefined;
        this.dialogAlertVisible = false;
      });
    },

    /**
     * 组合下单按钮点击
     */
    handleCombinationOrderBtnClick(row) {
      this.combinationOrder.show = true;
      this.combinationOrder.orderId = row.orderId;
      this.combinationOrder.loading = true;
      CombineApi.listRemainingGoods({ orderId: this.combinationOrder.orderId })
        .then((res) => {
          this.combinationOrder.loading = false;
          this.combinationOrder.table = res.data;
        })
        .catch(() => {
          this.combinationOrder.loading = false;
        });
    },

    /**
     * 组合下单列表选中change
     */
    handleCombinationOrderTableSelectionChange(value) {
      this.combinationOrder.selected = value;
    },

    /**
     * 组合下单
     */
    handleCombinationOrderSubmit() {
      const { selected, orderId } = this.combinationOrder;
      if (selected.length === 0) {
        this.$message.error('请先选择一项');
        return false;
      }
      const params = {
        orderId,
        list: selected.map((item) => {
          return { nums: 1, goodsType: item.goodsType, variantId: item.variantId, name: item.name };
        }),
      };
      this.combinationOrder.loading = true;
      OrderApi.combineAdditionOrder(params)
        .then((res) => {
          this.combinationOrder.show = false;
          this.combinationOrder.loading = false;
          this.$message.success('组合下单成功');
          this.listData();
        })
        .catch(() => {
          this.combinationOrder.loading = false;
        });
    },
    handleAddRemark(row) {
      this.orderId = row.orderId;
      this.remarkShow = true;
    },
    remarkClick(i) {
      if (i == 1) {
        if (!this.remarkVal) {
          this.$message.error('请填写备注内容');
          return false;
        }
        OrderApi.OrderAddReamrk({
          orderRemark: this.remarkVal,
          orderId: this.orderId,
        })
          .then((res) => {
            if (res.status === 0) {
              this.$message.success('操作成功');
              this.remarkShow = false;
              this.remarkVal = '';
            }
          })
          .catch((err) => {});
      } else {
        this.remarkShow = false;
        this.remarkVal = '';
      }
    },
    addToConfirm() {
      if (this.alarmType == '') {
        this.$message.error('请选择报警类型');
        return false;
      }
      OrderApi.addToOrder({ orderId: this.orderId, alarmType: this.alarmType }).then((res) => {
        if (res.status == 0) {
          this.$message({
            type: 'success',
            message: '操作成功！',
          });
          this.addToCancel();
        }
      });
    },
    addToCancel() {
      this.alarmType = '';
      this.orderId = '';
      this.addToShow = false;
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
<style lang="scss" scoped>
.modify-price {
  .el-row {
    line-height: 35px;
    font-size: 15px;

    .el-col {
      margin: 4px 0;

      &::v-deep .el-input__inner {
        width: 250px !important;
      }

      &::v-deep .el-textarea__inner {
        width: 250px !important;
        height: 100px;
      }
    }

    .el-col:first-of-type {
      text-align: end;
    }
  }
}

.take-order {
  .item {
    margin-top: 15px;
    width: 100%;
  }
}

.img-wrapper {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;

  .img-item {
    position: relative;

    .el-image {
      width: 200px;
      height: 200px;
      flex-shrink: 0;
      margin-bottom: 10px;
    }

    .el-icon-circle-close {
      cursor: pointer;
      position: absolute;
      right: -5px;
      top: -5px;
      font-size: 25px;
    }
  }

  .upload-img {
    flex-shrink: 0;
    margin-bottom: 10px;

    ::v-deep .el-upload-dragger {
      width: 200px;
      height: 200px;
    }
  }
}

.flex-box {
  .item {
    display: flex;
    line-height: 50px;
    font-size: 16px;

    .label {
      width: 280px;
    }
  }
}
</style>
